package com.example.wearing.find;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.tools.ImageUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddPostActivity extends AppCompatActivity implements Runnable {

    private static final String TAG = "AddPostActivity";

    public static final int RESQUEST_CODE_TAKE = 1;
    public static final int RESQUEST_CODE_CHOOSE = 2;
    private Uri imageUri;
    private String imageBase64, postUser, postTitle, postDetail, postTime;
    private int postUid;
    private String imageUrl = "";
    private Handler handler;
    private ImageView addImgBtn;
    private EditText p_title, p_detail;
    private String jdbcUser, jdbcUrl, jdbcPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_post);

        addImgBtn = findViewById(R.id.addImgBtn);
        p_title = findViewById(R.id.addTitle);
        p_detail = findViewById(R.id.addDetail);
        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    //点击“发布”
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public void publishPost(View view){

        postTitle = p_title.getText().toString().trim();
        postDetail = p_detail.getText().toString().trim();

        //设置标题和详情不为空
        if(postTitle.isEmpty()){
            Toast.makeText(getApplicationContext(), "请填写标题", Toast.LENGTH_LONG).show();
            return;
        }else if(postDetail.isEmpty()){
            Toast.makeText(getApplicationContext(), "请填写详细内容", Toast.LENGTH_LONG).show();
            return;
        }else if(imageUrl.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择图片", Toast.LENGTH_LONG).show();
            return;
        }

        //从SharedPreferences中获取用户名
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        postUser = sp.getString("user_name","");
        postUid = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

        //获取当前时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        Log.i(TAG, "获取当前时间:"+date);
        postTime = formatter.format(date);

        Log.i(TAG, "publishPost: string长度："+imageBase64.length());

        Toast.makeText(getApplicationContext(), "正在提交，请稍等~", Toast.LENGTH_SHORT).show();

        //上传数据到表中
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");
                if(msg.what == 1){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        //发布成功
                        Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                        //返回帖子界面
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };


        Thread thread = new Thread(this);
        thread.start();

    }




    //点击添加照片，弹出相册
    public void chooseImage(View view){

        Log.i(TAG, "onClick: 相册");
        //从相册选取照片
        if(ContextCompat.checkSelfPermission(AddPostActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //真正去打开相册
            openAlbum();
        }else{
            //去申请权限
            ActivityCompat.requestPermissions(AddPostActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

    }

    //权限管理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 0) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else{
                Toast.makeText(this, "您没有获得访问相册权限~", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESQUEST_CODE_CHOOSE){
            //从相册选取照片
            Uri uri = data.getData();
            String path = null;
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if(cursor != null) {
                if(cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                cursor.close();
            }
            if(path != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                imageUrl = path;
                Log.i(TAG, "onActivityResult: path:"+path);///storage/emulated/0/DCIM/Camera/IMG_20220301_180527.jpg

                addImgBtn.setImageBitmap(bitmap);
                String imageToBase64 = ImageUtil.imageToBase64(bitmap);
                imageBase64 = imageToBase64;
            }
        }
    }

    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, RESQUEST_CODE_CHOOSE);
    }


    //创建线程类，实现Runnable接口，用于存入数据库
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void run() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
            Statement st = (Statement)cn.createStatement();
            int insertCode;
            try {
                String insertSql = "INSERT INTO post (p_title,p_detail,p_img,p_time,p_uid,p_likeNum,p_replyNum) VALUES ('"+postTitle+"','"+postDetail+"','"+imageBase64+"','"+postTime+"',"+postUid+",0,0)";
                int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                Log.i(TAG, "run: 插入数据成功"+result+"行----"+postUser);
                insertCode = 1;

            } catch (SQLException e) {
                insertCode = 2;
                Log.i(TAG, "run:SQL fail!!!__"+e);
                e.printStackTrace();
            }

            //发送消息
            Message msg = handler.obtainMessage(1, insertCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---插入结果");

            st.close();
            cn.close();
        } catch (ClassNotFoundException | SQLException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        }
    }

}